package com.vanzo.contact;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.vanzo.bean.Contact;
import com.vanzo.bean.ContactDaoUtil;
import com.vanzo.talkie2.R;

import java.util.List;


/**
 * Created by tisen on 2018/1/17.
 */

public class ContactsActivity extends AppCompatActivity {

    public static final int CONTACTS_CHANGE = 1234;
    private static final String TAG = "ContactsActivity";


    private RecyclerView contactsRecycler;
    private PinYinSlideView pinYinSlideView;
    private CircleTextView circleTextView;

    private ImageView add_img;
    private ContactsAdapter contactsAdapter;
    private LinearLayoutManager layoutManager;
    private List<Contact> contacts;
    private AlertDialog.Builder builder;

    private ContactDaoUtil contactDaoUtil;
    private Long tempId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        contacts = initContacts();
        contactsRecycler = (RecyclerView) findViewById(R.id.contacts_recycler);
        pinYinSlideView = (PinYinSlideView) findViewById(R.id.pinyin_slide);
        circleTextView = (CircleTextView) findViewById(R.id.circle_text);
        add_img = (ImageView) findViewById(R.id.contact_add);
        layoutManager = new LinearLayoutManager(this);
        contactsRecycler.setLayoutManager(layoutManager);
        contactsAdapter = new ContactsAdapter(this, contacts);
        contactsRecycler.setAdapter(contactsAdapter);
        contactsAdapter.setItemOnClickListener(new ContactsAdapter.ItemOnClickListener() {
            @Override
            public void onClick(Long id) {
                showMenu(id);
//                Toast.makeText(getBaseContext(), "click " + position, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(Long id) {
//                Toast.makeText(getBaseContext(), "long click " + position, Toast.LENGTH_SHORT).show();
            }
        });
        pinYinSlideView.setOnShowTextListener(new PinYinSlideView.OnShowTextListener() {
            @Override
            public void showText(String text) {
                circleTextView.setText(text);
//                ToastUtils.display(getBaseContext(), "text = " + text);
                if (text != null) {
                    if (!text.equals("↑")) {
                        int position = 0;
                        boolean hasPinyin = false;
                        for (int i = 0; i < contacts.size(); i++) {
                            Contact contact = contacts.get(i);
                            if (contact.getPinyin().substring(0, 1).toUpperCase().equals(text)) {
                                position = i;
                                hasPinyin = true;
                                break;
                            }
                        }
                        if (hasPinyin) {
                            ContactsActivity.this.scrollToPosition(position);
                        }
                    }
                } else {

                }
            }
        });
        contactsRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstItem = layoutManager.findFirstVisibleItemPosition();
                Contact contact = contactsAdapter.getItem(firstItem);
                if (contact != null) {
                    circleTextView.setText(contact.getPinyin().substring(0, 1).toUpperCase());
                }


            }
        });
        add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ContactsActivity.this, ContactAddActivity.class);
                intent.setAction(ACTION_ADD);
                startActivityForResult(intent, 0);
            }
        });
    }

    private void showMenu(Long id) {
        tempId = id;
        if (builder == null) {
            builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.menu_dialog_title);
            builder.setItems(R.array.menu_items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
//                    Toast.makeText(getBaseContext(), "click " + which, Toast.LENGTH_SHORT).show();
                    menuOption(which, tempId);
                }
            });
        }
        builder.create().show();
    }

    private void menuOption(int which, Long id) {
        Contact contact = contactDaoUtil.queryContactById(id);
        switch (which) {
            case 0:
                if (contact.getPhone().trim().isEmpty()) {
                    Toast.makeText(this, "手机号码为空", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact.getPhone()));
                    startActivity(intent);
                }
                break;
            case 1:
                sendMsg(contact);
                break;
            case 2:
                sendHelp(contact);
                break;
            case 3:
                Intent intent1 = new Intent(this, ContactAddActivity.class);
                intent1.setAction(ACTION_VIEW);
                intent1.putExtra("id", id);
                startActivity(intent1);
                break;
            case 4:
                Intent intent2 = new Intent(this, ContactAddActivity.class);
                intent2.setAction(ACTION_EDIT);
                intent2.putExtra("id", id);
                startActivityForResult(intent2, 0);
                break;
            case 5:
                contactDaoUtil.deleteContact(contact);
                notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == CONTACTS_CHANGE) {
            notifyDataSetChanged();
        }
    }

    private void notifyDataSetChanged() {
        contacts = contactDaoUtil.queryAllContact();
        contactsAdapter.setContacts(contacts);
    }

    private static int ADD_REQUEST_CODE = 101;
    private static int VIEW_REQUEST_CODE = 101;
    private static int EDIT_REQUEST_CODE = 101;

    public static final String ACTION_ADD = "action.add";
    public static final String ACTION_VIEW = "action.view";
    public static final String ACTION_EDIT = "action.edit";


    private void scrollToPosition(int position) {
        if (position >= 0 && position <= contactsAdapter.getItemCount() - 1) {
            int firstIndex = layoutManager.findFirstVisibleItemPosition();
            int lastIndex = layoutManager.findLastVisibleItemPosition();
            if (position <= firstIndex) {
                contactsRecycler.scrollToPosition(position);
            } else if (position <= lastIndex) {
                int top = contactsRecycler.getChildAt(position - firstIndex).getTop();
                contactsRecycler.scrollBy(0, top);
            } else {
                contactsRecycler.scrollToPosition(position);
                mIndex = position;
            }
        }
    }

    private int mIndex = 0;

    private List<Contact> initContacts() {
        if (contactDaoUtil == null) {
            contactDaoUtil = new ContactDaoUtil(this);
        }
//        String[] names = new String[]{"AliBaBa", "Baidu", "TaoBao", "hehe", "宋爱梅", "王志芳", "于光", "贾隽仙", "贾燕青", "刘振杰", "郭卫东", "崔红宇", "马福平", "冯红", "崔敬伟", "穆增志", "谢志威", "吕金起", "韩云庆", "鲁全福", "郭建立", "郝连水", "闫智胜"};
//
//
//        List<Contact> mContacts = new ArrayList<>();
//        for (String name :
//                names) {
//            Contact contact = new Contact();
//            contact.setName(name);
//            contact.setPhone("15000531187");
//            mContacts.add(contact);
//        }
//        Collections.sort(mContacts);
////        Log.d(TAG, Arrays.toString(mContacts.toArray()));
        return contactDaoUtil.queryAllContact();
    }

    public void sendMsg(Contact contact) {

    }

    public void sendHelp(Contact contact) {

    }
}
